﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallERP.Bll.PinBan;
using SmallERP.MODEL.PBModel;
using SmallERP.PinBan.PB.Presenter;
using Small.PinBan.PB.View;
using SmallERP.MODEL.FoundationModel;
using Small.PinBan.PB.Comm;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using SmallERP.PinBan.PB.Froms;
using Small.PinBan.PB.Froms;
using Smallerp.Contracts.DataContracts;
using System.ServiceModel;
using Smallerp.Contracts;
using Leadtools.Codecs;
using System.ComponentModel;
using SmallERP.PinBan;


namespace Small.PinBan.PB.Presenter
{
    /// <summary>
    /// 方向
    /// </summary>
    enum DirEmu
    {
        LeftUp = 1,//左上
        LeftDown = 2,//左下
        RightDown = 3,//右下
        RightUp = 4,//右上

        Left = 5,
        Right,
        Up,
        Down
    }

    public class PBMainPresenter
    {

        private OrderBLL _bll;
        private IPBMainView _view;

        private List<OrderInfo_PBDCT> _allOrderList = new List<OrderInfo_PBDCT>();//从数据库取得的所有符合条件的产品列表
        /// <summary>
        /// 当前显示的产品的集合，包括所有操作、过泋后的
        /// </summary>
        private List<OrderInfo_PBDCT> _curBindOrderList = new List<OrderInfo_PBDCT>();//当前绑定到GV中的产品列表（将进行产品快速过滤后的结果）
        private List<OrderInfo_PBDCT> _selectedOrderList = new List<OrderInfo_PBDCT>();//被用户多选的产品列表,即将前有效的产品列表，可以用来半自动拼板、和全自动拼板的结果集

        private List<string> _photoSizeList = new List<string>();                        //存放照片尺寸列表
        private List<PicView> _ListPicView = new List<PicView>();                        //用于存放被拖到大纸上所有的图片集合
        private PicView _multilSelectTPicV;//存入多选后形成的那个大的PICV
        private List<PicView> _mulSelPicVList;//被多选的那些图片的集合
        private bool _isNewPhotoList = false;                       //照片列表是否是新的，即主要是不同的打印机、纸型、纸面决定了照片列表是否是新的

        private Point _PicEnablePoint = new Point(-1, -1);          //在拖动释放的那一刻，图片能放到的有效的坐标
        private float _curWraste = 0;                               //当前浪费率
        private int _curMaxX = 0;                                   //当前最大的X值
        private int _FactMaxX = 0;

        private double PlusValues = 0.04;

        public PBMainPresenter()
        {            
           
        }

        public PBMainPresenter(IPBMainView view)
        {
            _view = view;
            
            _view._proxyOperateDB = new ChannelFactory<IOperateDB>("IOperateDB");
            _view._OperateDb = _view._proxyOperateDB.CreateChannel();
            try
            {

                _bll = new OrderBLL(DataTransfer.IPadress, DataTransfer.Port, _view._OperateDb);              
            }
            catch (EndpointNotFoundException ex)
            {
                MessageBox.Show("无法连接到:" + DataTransfer.IPadress+":"+DataTransfer.Port);
                Environment.Exit(1);
            }
            catch (Exception exx)
            {
                MessageBox.Show("网络错误：" + exx.Message);
                Environment.Exit(1);
            }
            //if (IniliData())
            //{
            _view.InitCtlsLoaction();
            _view.DrawScaleLine();
            //}
            //else
            //{
            //    Application.Exit();
            //}
            bgwFullPB.WorkerReportsProgress = true;
            bgwFullPB.WorkerSupportsCancellation = true;
            bgwFullPB.ProgressChanged += new ProgressChangedEventHandler(bgwFullPB_ProgressChanged);
            bgwFullPB.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwFullPB_RunWorkerCompleted);
            bgwFullPB.DoWork += new DoWorkEventHandler(bgwFullPB_DoWork);
            timeFullPB.Interval = 2000;
            timeFullPB.Tick += new EventHandler(timeFullPB_Tick);
        }

        void bgwFullPB_DoWork(object sender, DoWorkEventArgs e)
        {
            decimal waste = Convert.ToDecimal(e.Argument);
            List<PhotoInfo_PBDCT> listResult;
            if (currPhotoList.Count > 0)
            {
                decimal outWaste = 0;
                int currLength;
                try
                {
                    //listResult = _bll.AutoPinSN(_allOrderList.Select(o => o.PhotoList).ToList(), DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (decimal)waste,out outWaste);
                    listResult = _bll.AutoPinSN(currPhotoList, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (decimal)waste, out outWaste, out currLength, (int)PBDataTransfer.SmallType);
                    //int maxy2 = listResult.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI)));
                    if (listResult != null && listResult.Count > 0)
                    {
                        int aa = _bll.CreateBoard2(listResult, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (float)outWaste, currLength, false,true);
                        if (aa > 0)
                        {
                            bgwFullPB.ReportProgress(0);
                        }
                        else
                        {

                        }
                    }
                    else
                    {
                        bgwFullPB.ReportProgress(100);

                    }
                }
                catch (Exception ex)
                {
                    bgwFullPB.ReportProgress(1, ex);
                }
            }

        }
        List<List<PhotoInfo_PBDCT>> currPhotoList = new List<List<PhotoInfo_PBDCT>>();
        private void AddNew()
        {
            currPhotoList = _allOrderList.Select(o => o.PhotoList).ToList();
            RushBind(true);
        }

        void bgwFullPB_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
        int AutoPBCount = 0;
        void bgwFullPB_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)
            {
                AutoPBCount++;
                _view.RefushAutoNum(AutoPBCount);
            }
            else if (e.ProgressPercentage == 100)
            {
                AddNew();
            }
            else if (e.ProgressPercentage == 1)
            {
                MessageBox.Show("错误信息：" + e.UserState.ToString());
            }
        }

        void timeFullPB_Tick(object sender, EventArgs e)
        {
            if (!bgwFullPB.IsBusy)
            {
                bgwFullPB.RunWorkerAsync(CurrWaste);
            }
            //throw new NotImplementedException();
        }

        #region 测试用数据

        private void CreateTestPrinter()
        {
            DataTransfer.CurPrinerInfo = new PrinterDCT()
            {
                PrinterID = 1,
                HotDirPath = "",
                PDPI = 254

            };
        }

        private void CreateTestTemlate()
        {
            DataTransfer.curTemplateInfo = new BoardTemplate_DCT()
            {
                BarCodeStatus = 0,
                Height = 30,
                Length = 80,
                PaperFaceId = 2,
                PaperFaceName = "光面",
                PaperTypeId = 2,
                PaperTypeName = "柯达",
                TemplateId = 1,
                TemplateName = "测试模板"
            };
        }
        #endregion



        public bool IniliData()
        {
            if (DataTransfer.CurPrinerInfo == null)
            {
                BindPrinter();
                if (DataTransfer.AllPrinterList.Count < 0)
                {
                    MessageBox.Show("请先建立打印机，再拼板");
                    return false;
                }
            }
            try
            {
                FrmSelectedPrinter frmSelPrinter = new FrmSelectedPrinter();
                if (frmSelPrinter.ShowDialog() != DialogResult.OK)
                {
                    return false;
                }
                _view.ShowParas(DataTransfer.CurPrinerInfo);
                //if (DataTransfer.curTemplateInfo == null)
                //{
                BindBoardTemplate();
                if (DataTransfer.curTemplateInfo == null)
                {
                    FrmTemplateManager frmTm = new FrmTemplateManager(_view._OperateDb);
                    frmTm.ShowDialog();
                    MessageBox.Show("没有可用的模板，请选建立模板");
                }
                //}        

                RushBind();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return true;
        }

        /// <summary>
        /// 得到所有打印机
        /// </summary>
        private void BindPrinter()
        {
            if (_bll != null)
            {
                DataTransfer.AllPrinterList = _bll.GetAllPrinters();
            }
        }

        /// <summary>
        /// 绑定大板的模板列表
        /// </summary>
        private void BindBoardTemplate()
        {
            BoardTemplateBLL boardTemp = new BoardTemplateBLL(_view._OperateDb);
            if (DataTransfer.CurPrinerInfo == null)
            {
                CreateTestPrinter();
            }
            DataTransfer.BoardTempalteList = boardTemp.GetAllTemplate(DataTransfer.CurPrinerInfo);
            DataTransfer.curTemplateInfo = DataTransfer.BoardTempalteList.FirstOrDefault();
            if (DataTransfer.curTemplateInfo == null)
            {
                //跳出建模板的界面
                TemplateManage();
                //FrmTemplateManager frmTempalteManger = new FrmTemplateManager();
                //frmTempalteManger.ShowDialog();
                //BindBoardTemplate();
            }
            else
            {
                _view.BindTemplateCmd(DataTransfer.BoardTempalteList);
            }


        }

        /// <summary>
        /// 从数据库中得到所有产品并放到_allOrderList中
        /// </summary>
        public void GetOrderFromDB()
        {
            List<OrderInfo_PBDCT> resltOrdersList = null;
            int result = _bll.GetAllOrderInfoByTemplate(DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, out resltOrdersList);
            if (result == -1)
            {
                System.Windows.Forms.MessageBox.Show("没有可用的模板", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (resltOrdersList != null && resltOrdersList.Count > 0)
                {
                    _allOrderList = resltOrdersList;
                    BindPhotoSizeList();
                }
                else
                {
                    if (_allOrderList != null)
                    {
                        _allOrderList.Clear();
                    }
                    else
                    {
                        _allOrderList = new List<OrderInfo_PBDCT>();
                    }
                    System.Windows.Forms.MessageBox.Show("没有可拼板的图片","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// 从新从数据库中刷新列表
        /// </summary>
        internal void RushBind()
        {
            RushBind(true);
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="refush">是否要从数据库取数据，true-是，false-不需要</param>
        internal void RushBind(bool refush)
        {

            if (refush)
            {
                //ClearBigBoard();
                _isNewPhotoList = true;
                GetOrderFromDB();
            }
            BindSuitOrder(_allOrderList);
            _view.ShowWaste(PBDataTransfer.Waste);
        }
        internal void RushBindNew(List<PhotoInfo_PBDCT> inList)
        {
            ClearBigBoard();
            _isNewPhotoList = true;
            _allOrderList.ForEach(o => o.PhotoList.RemoveAll(delegate(PhotoInfo_PBDCT photo)
            {
                if (inList.FirstOrDefault(p => p.PhotoId == photo.PhotoId) != null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }));
            //List<OrderInfo_PBDCT> tempList = new List<OrderInfo_PBDCT>();
            //foreach (OrderInfo_PBDCT or in _allOrderList)
            //{

            //    foreach (PhotoInfo_PBDCT ph in or.PhotoList)
            //    {
            //        if (inList.FirstOrDefault(p => p.PhotoId == ph.PhotoId) != null)
            //        {
            //            or.PhotoList.Remove(ph);
            //        }

            //    }

            //    if (or.PhotoList.Count > 0)
            //    {
            //        tempList.Add(or);
            //    }


            //}
            List<OrderInfo_PBDCT> tempList = new List<OrderInfo_PBDCT>();
            foreach (OrderInfo_PBDCT or in _allOrderList)
            {
                if (or.PhotoList.Count > 0)
                {
                    tempList.Add(or);
                }

            }
            _allOrderList = tempList;
            BindSuitOrder(_allOrderList);
            BindPhotoSizeList();
        }


        internal void CancelMutilSelect()
        {
            //删除多选产生的那个Temp图片
            //将被选的小图片改变状态、还原事件、还原坐标

            if (_mulSelPicVList != null && _multilSelectTPicV != null)
            {
                _ListPicView.Remove(_multilSelectTPicV);
                _multilSelectTPicV.Visible = false;

                foreach (var pic in _mulSelPicVList)
                {
                    pic.Location = new Point(pic.Location.X + _multilSelectTPicV.Location.X, pic.Location.Y + _multilSelectTPicV.Location.Y);

                    ///这里添加 多选后 照片的实际位置重新计算
                    pic.PixFactX += _multilSelectTPicV.PixFactX;
                    pic.PixFactY += _multilSelectTPicV.PixFactY;
                    pic.Type = 0;

                    //      取消事件          
                    pic.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPName.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPSize.MouseDown -= new MouseEventHandler(_lblPSize_MouseDown);

                    //添加事件
                    pic.MouseDown += new MouseEventHandler(picV_MouseDown);
                    pic.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                    pic.KeyPress += new KeyPressEventHandler(picV_KeyPress);
                    pic._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);


                    _view.ShowPic(pic);
                }

                _multilSelectTPicV.Dispose();
                _multilSelectTPicV = null;
                _mulSelPicVList.Clear();
            }
        }

        internal void MultiSelectedPic(Small.PinBan.PB.Comm.PicView pv, List<Small.PinBan.PB.Comm.PicView> selectedCtrls)
        {
            //1.当新的大图PV加入到_ListPicView
            //2.改变被选图片的type=2
            //3.调整被选图片的相对坐标，及所属父容器
            //4.注册相应的事件，如移动，删除、mouseDown事件等
            //5.改变被选图片的相应事件
            _multilSelectTPicV = pv;
            _mulSelPicVList = selectedCtrls;
            Point p;
            pv.MouseDown += new MouseEventHandler(picV_MouseDown);
            pv.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
            pv.KeyPress += new KeyPressEventHandler(picV_KeyPress);


            _ListPicView.Add(pv);


            foreach (var pic in selectedCtrls)
            {

                pic.Type = 2;

                //取消事件
                pic.MouseDown -= new MouseEventHandler(picV_MouseDown);
                pic.PicMoveEvent -= new MyPicViewMoveHandler(picV_PicMoveEvent);
                pic.KeyPress -= new KeyPressEventHandler(picV_KeyPress);
                pic._lblPName.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                pic._lblPSize.MouseDown -= new MouseEventHandler(_lblPSize_MouseDown);


                //加入事件
                pic.MouseDown += new MouseEventHandler(_lblPName_MouseDown);




                p = pic.Location;
                p.Offset(-pv.Location.X, -pv.Location.Y);
                pic.PixFactX -=pv.PixFactX;
                pic.PixFactY -= pv.PixFactY;
                pic.Location = p;
                pv.Controls.Add(pic);
            }
        }

        private void picV_KeyPress(object sender, KeyPressEventArgs e)//旋转、删除操作
        {
            PicView picCur = (PicView)sender;
            if (e.KeyChar == (int)Keys.Space)//旋转
            {
                #region 旋转方向
                //PicView picCur = (PicView)sender;

                if (picCur.Type == 1)//多选中的temp大图
                {
                    return;
                }
                int newWidth = 0, newHeight = 0;
                PicView tempPic;
                bool isRect;
                int newPixWidth, newPixHeight = 0;
                if (picCur.PInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)
                {
                    newWidth = picCur.Height - DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width + DataTransfer.BarCodePixWidth;

                    newPixWidth = picCur.PixFacHeight - DataTransfer.BarCodePixFactWidth;
                    newPixHeight = picCur.PixFacWidth + DataTransfer.BarCodePixFactWidth;

                }
                else if (picCur.PInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)
                {
                    newWidth = picCur.Height + DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width - DataTransfer.BarCodePixWidth;

                    newPixWidth = picCur.PixFacHeight + DataTransfer.BarCodePixFactWidth;
                    newPixHeight = picCur.PixFacWidth - DataTransfer.BarCodePixFactWidth;

                }
                else//无条码
                {
                    newWidth = picCur.Height;
                    newHeight = picCur.Width;

                    newPixWidth = picCur.PixFacHeight ;
                    newPixHeight = picCur.PixFacWidth;
                }

                tempPic = new PicView(picCur.PInfo, newWidth, newHeight, picCur.Location);
                //tempPic.PixFacWidth = newPixWidth;
                //tempPic.PixFacHeight = newPixHeight;
                tempPic.PixFactX = picCur.PixFactX;
                tempPic.PixFactY = picCur.PixFactY;
                Point pt = tempPic.Location;
                bool result = GetSuitPoint(ref pt, tempPic);
                if (result == false)
                {
                    tempPic.Dispose();
                    return;
                }
                tempPic.Location = pt;

                isRect = IsInRect(tempPic);
                if (!isRect)
                {
                    picCur.Location = tempPic.Location;
                    picCur.Width = newWidth;
                    picCur.Height = newHeight;

               
                    picCur.IsWhirl = !picCur.IsWhirl;
                    ShowWraste();
                }
                tempPic.Dispose();
                #endregion
            }
            else if (e.KeyChar == 100 || e.KeyChar == (int)Keys.Delete || e.KeyChar == (int)Keys.D)//删除
            {
                #region 删除选中图片
                //PicView picCur = (PicView)sender;
                if (picCur.Type == 1)//多选删除
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        foreach (var pic in _mulSelPicVList)
                        {
                            OrderInfo_PBDCT oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == pic.PInfo.Photo_Base_Info.OrderProductId);
                            if (oi != null)
                            {
                                PhotoInfo_PBDCT pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);

                                if (pi != null)
                                {
                                    pi.IsInBoard = false;
                                    pi.IsWhirl = false;
                                }
                                _ListPicView.Remove(pic);
                                //_OveredPointList.Remove(pic.Location);
                                pic.Dispose();
                                CheckOrdersPhotoIsAllInBoard(pic.PInfo.OrderProductId);
                            }

                            //检果访照片所对应的产品的其它照片是否都已放到大板上
                            CheckOrdersPhotoIsAllInBoard(pic.PInfo.OrderProductId);
                        }

                        _mulSelPicVList.Clear();
                        _multilSelectTPicV.Dispose();
                        _multilSelectTPicV = null;
                        picCur.Dispose();
                        _ListPicView.Remove(picCur);
                    }
                }
                else//单选删除
                {
                    //PhotoInfo_PinBan pi = _photosList.FirstOrDefault(p => p.PhotoId == picCur.PInfo.PhotoId);
                    OrderInfo_PBDCT oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == picCur.PInfo.Photo_Base_Info.OrderProductId);
                    if (oi != null)
                    {
                        PhotoInfo_PBDCT pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == picCur.PInfo.PhotoId);
                        if (pi != null)
                        {
                            pi.IsInBoard = false;
                            pi.IsWhirl = false;
                            //_OveredPointList.Remove(pi.Location);
                            picCur.Dispose();
                        }
                    }
                    _ListPicView.Remove(picCur);
                    CheckOrdersPhotoIsAllInBoard(picCur.PInfo.OrderProductId);
                }
                _view.RefushMainGrid();
                ShowWraste();

                #endregion
            }
            else if (e.KeyChar == (int)Keys.F || e.KeyChar == 102)//将条码在上下部或是左右部切换
            {
                #region 切换条码的方向
                if (picCur.Type == 1)//多选中的temp大图
                {
                    return;
                }
                if (picCur.PInfo.BarCodeStatus != SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode)//有条码
                {
                    int newWidth = 0, newHeight = 0;
                    int newPixWidth, newPixHeight = 0;
                    SmallERP.COM.Status.PhotoBarCodeStatus tempBarCodeStatus = picCur.PInfo.BarCodeStatus;
                    PicView tempPic;
                    bool isRect;

                    if (picCur.PInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)//条码在左右,切换到上下
                    {
                        newWidth = picCur.Width - DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height + DataTransfer.BarCodePixWidth;
                        
                        tempBarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom;

                        newPixWidth = picCur.PixFacWidth - DataTransfer.BarCodePixFactWidth;
                        newPixHeight = picCur.PixFacHeight + DataTransfer.BarCodePixFactWidth;
                    }
                    else//条码在上下,切换到左右
                    {
                        newWidth = picCur.Width + DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height - DataTransfer.BarCodePixWidth;
                        tempBarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft;


                        newPixWidth = picCur.PixFacWidth + DataTransfer.BarCodePixFactWidth;
                        newPixHeight = picCur.PixFacHeight - DataTransfer.BarCodePixFactWidth;
                    }

                    tempPic = new PicView(picCur.PInfo, newWidth, newHeight, picCur.Location);
                 
                    Point pt = tempPic.Location;
                    bool result = GetSuitPoint(ref pt, tempPic);
                    if (result == false)
                    {
                        tempPic.Dispose();
                        return;
                    }
                    tempPic.Location = pt;
                    isRect = IsInRect(tempPic);

                    if (!isRect)
                    {
                        picCur.Location = tempPic.Location;
                        picCur.Width = newWidth;
                        picCur.Height = newHeight;

                      


                        picCur.PInfo.BarCodeStatus = tempBarCodeStatus;
                        ShowWraste();
                    }
                    tempPic.Dispose();
                }
                #endregion
            }
            else if (e.KeyChar == (int)Keys.T || e.KeyChar == 116)//选中的图片之打印一张图片的条码，其它照片无条码
            {
                #region
                if (picCur.Type == 1)
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        if (MessageBox.Show("确定要将选中的照片只打印一张条码？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            return;
                        }
                        bool isSet = false;
                        foreach (var pic in _mulSelPicVList)
                        {
                            if (!isSet)
                            {
                                isSet = true;
                                continue;
                            }

                            OrderInfo_PBDCT oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == pic.PInfo.Photo_Base_Info.OrderProductId);
                            if (oi != null)
                            {
                                PhotoInfo_PBDCT pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);

                                if (pi != null)
                                {
                                    int newWidth = 0, newHeight = 0;
                                    if (pi.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)//条码在左右,切换到无条码
                                    {
                                        newWidth = pic.Width - DataTransfer.BarCodePixWidth;
                                        newHeight = pic.Height;

                                    }
                                    else//条码在上下,切换到无条码
                                    {
                                        newWidth = pic.Width;
                                        newHeight = pic.Height - DataTransfer.BarCodePixWidth;
                                    }

                                    pic.Width = newWidth;
                                    pic.Height = newHeight;
                                    pi.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode;
                                }
                            }
                        }
                    }
                }

                #endregion
            }
            else if (e.KeyChar == (int)Keys.W)//有条码和无条码之间切换
            {
                #region
                //if (picCur.Type == 1)
                //{
                //    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                //    {
                //        if (MessageBox.Show("确定要将选中的照片只打印一张条码？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                //        {
                //            return;
                //        }            
                //        foreach (var pic in _mulSelPicVList)
                //        {
                //            OrderInfo_PBDCT oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == pic.PInfo.Photo_Base_Info.OrderProductId);
                //            if (oi != null)
                //            {
                //                PhotoInfo_PBDCT pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);

                //                if (pi != null)
                //                {
                //                    int newWidth = 0, newHeight = 0;
                //                    if (pi.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode)//条码在左右,切换到无条码
                //                    {
                //                        switch (DataTransfer.curTemplateInfo.BarCodeStatus)//大板的条码状态是什么样的
                //                        {
                //                            case SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft://从无条码变成左边放条码
                //                                pic.Width = newWidth;
                //                                newHeight = picCur.Height - DataTransfer.BarCodePixWidth;

                //                                break;
                //                            case SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom:
                //                                break;
                //                            case SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode:
                //                                break;
                //                            default:
                //                                break;
                //                        }


                //                    }
                //                    //else//条码在上下,切换到无条码
                //                    //{
                //                    //    newWidth = picCur.Width;
                //                    //    newHeight = picCur.Height - DataTransfer.BarCodePixWidth;
                //                    //}

                //                    pic.Width = newWidth;
                //                    pic.Height = newHeight;
                //                    pi.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode;
                //                }
                //            }
                //        }
                //    }
                //}

                #endregion
            }
        }

        private void _lblPSize_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }

        private void _lblPName_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }


        #region help methods

        //移动图片
        [DllImport("user32")]
        public static extern int IntersectRect(ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpDestRect, ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpSrc1Rect, ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpSrc2Rect);

        void picV_PicMoveEvent(PicView sender, Point newPoint) //移动图片
        {

            Point CurPoint = newPoint;
            Point controlLocation = sender.Parent.PointToClient(CurPoint);//当前PIC控件在PANEL中的location相对坐标位置

            GetSuitPoint(ref controlLocation, sender);

            if (sender.LeftAnchor || sender.RightAnchor)
            {
                controlLocation.X = sender.Left;
            }
            if (sender.UpAnchor || sender.DownAnchor)
            {
                controlLocation.Y = sender.Top;
            }

            PicView _tempPicView = new PicView(sender.PInfo, sender.Width, sender.Height, controlLocation);
            bool result = false;
            List<PicView> overPicList = null;//如果重叠的话，记录重叠的图片集合

            if (!_tempPicView.IsOutRedLine)//红线外的不管
            {
                result = IsInRect(_tempPicView);
            }
            else
            {
                controlLocation = _tempPicView.Location;
            }

            if (result)//如果虚线框与其它图片重叠
            {
                #region //如果虚线框与其它图片重叠

                Point factPoint = sender.Location;//实框的坐标
                DirEmu direction = GetLoctionDirection(controlLocation, factPoint);//虚线框在实框的什么方位
                PicView overPic = null;
                switch (direction)
                {
                    case DirEmu.LeftUp:
                        #region 左上
                        sender.RightAnchor = false;
                        sender.DownAnchor = false;
                        while (factPoint.X - controlLocation.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            //if (sender.LeftAnchor && sender.UpAnchor)
                            //{
                            //    break;//上和左边都靠上了，再往左上移就不动
                            //}
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                                else
                                {
                                    factPoint.X = 0;
                                    sender.LeftAnchor = true;
                                }
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }

                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderByDescending(pv => pv.Bottom).ToList();
                            //bool hasOver = IsInRect(_tempPicView, ListPicView, out overPic);
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.LeftDown:
                        #region 左下

                        sender.RightAnchor = false;
                        sender.UpAnchor = false;

                        while (factPoint.X - controlLocation.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                            }
                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.ScreenBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.ScreenBoardHeight;
                                    sender.DownAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.RightDown:

                        #region 右下
                        sender.LeftAnchor = false;
                        sender.UpAnchor = false;

                        while (controlLocation.X - factPoint.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }

                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.ScreenBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.ScreenBoardHeight;
                                    sender.DownAnchor = true;
                                }

                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).ThenBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);


                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                Debug.WriteLine("重叠的照片ID：" + overPic.PInfo.PhotoId);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.RightUp:

                        #region 右上
                        sender.DownAnchor = false;
                        sender.LeftAnchor = false;

                        while (controlLocation.X - factPoint.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }

                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).OrderByDescending(pv => pv.Bottom).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }

                        }

                        sender.Location = factPoint;
                        #endregion
                        break;
                }

                #endregion
            }
            else
            {
                sender.Location = controlLocation;
                sender.LeftAnchor = false;
                sender.RightAnchor = false;
                sender.UpAnchor = false;
                sender.DownAnchor = false;
            }
            _view.RefushPanel();
            _PicEnablePoint = sender.Location;
        }

        /// <summary>
        /// 得到pv2相对于pv1的相对位置，这二个图都相邻且不相交的，上、下、左、右,pV1是移动的那图片，PV2是与PV1重叠的，即PV1要靠上PV2
        /// Pv1是不与PV2重叠前的最近的那个图形
        /// </summary>
        /// <param name="pv1"></param>
        /// <param name="pv2"></param>
        /// <returns></returns>
        private DirEmu GetTwoPicVRelativelyDir(PicView pv1, PicView pv2)
        {
            if (pv1.Left >= pv2.Right)
            {
                return DirEmu.Left;
            }
            if (pv1.Right <= pv2.Left)
            {
                return DirEmu.Right;
            }
            if (pv1.Top >= pv2.Bottom)
            {
                return DirEmu.Up;
            }
            if (pv1.Bottom <= pv2.Top)
            {
                return DirEmu.Down;
            }
            return 0;
        }

        /// <summary>
        /// 得到p1相对于P2的方位,左上、左下、右上、右下
        /// </summary>
        /// <param name="p1">虚线框的Location</param>
        /// <param name="p2">实框的Location</param>
        /// <returns></returns>
        private DirEmu GetLoctionDirection(Point p1, Point p2)
        {
            if (p1.X <= p2.X)
            {
                if (p1.Y <= p2.Y)
                {
                    return DirEmu.LeftUp;
                }
                else
                {
                    return DirEmu.LeftDown;
                }
            }
            else
            {
                if (p1.Y <= p2.Y)
                {
                    return DirEmu.RightUp;
                }
                else
                {
                    return DirEmu.RightDown;
                }
            }
        }


        #region 是否重叠


        private PicView _RedPicView;//代码红线的矩形框
        /// <summary>
        /// 判断图片是否和tarGetList集合中的有重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="tarGetList"></param>
        /// <param name="overPic">和PV重叠的那张图片</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv, List<PicView> tarGetList, out PicView overPic)
        {
            bool result = false;
            if (pv.IsOverRedLin)
            {
                if (_RedPicView == null)
                {
                    _RedPicView = new PicView(0, 1, DataTransfer.ScreenBoardHeight, new Point(DataTransfer.ScreenBoardLength, 0));
                }
                overPic = _RedPicView;
                //overPic = new PicView(0, 1, DataTransfer.inchBoardHeight, new Point(DataTransfer.inchBoardWidth, 0));
                return true;
            }
            overPic = null;
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT rectResult = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT();//如果相交的话，此值就不为空
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT curtRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(pv.Rect);


            foreach (var picV in tarGetList)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT PicVRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(picV.Rect);
                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    if (res > 0)
                    {
                        result = true;
                        overPic = picV;
                        break;
                    }
                }
            }

            return result;
        }




        /// <summary>
        ///  判断图片是否与其它已存在的图片重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="overPicList">与PV重叠的那些图片集合</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv)
        {
            bool result = false;
            //先得判断是否出拼板区的边界
            if (IsOverBoard(pv))
                return true;


            if (pv.IsOverRedLin)
            {
                return true;
            }

            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT rectResult = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT();//如果相交的话，些值就不为空
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT curtRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(pv.Rect);
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT curtFactRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(pv.PixFactRect);

            foreach (var picV in _ListPicView)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT PicVRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(picV.Rect);
                    DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT PicVFactRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(picV.PixFactRect);

                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    //int res = IntersectRect(ref rectResult, ref PicVFactRect, ref curtFactRect);
                    if (res > 0)
                    {
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }

        #endregion

        /// <summary>
        /// 查看图片是否超出了边界
        /// </summary>
        /// <param name="pv"></param>
        /// <returns></returns>
        private bool IsOverBoard(PicView pv)
        {
            if (pv.Location.X < 0)
            {
                return true;
            }
            if (pv.Location.Y < 0)
            {
                return true;
            }
            if (pv.Location.Y + pv.Height > DataTransfer.ScreenBoardHeight)
            {
                return true;
            }
            return false;
        }

        private bool GetSuitPoint(ref Point p, PicView pv)//得到符合大纸范围的合适的坐标,能否找到合适的位置
        {
            bool result = true;
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (p.Y < 0)
            {
                p.Y = 0;
            }
            if (p.Y + pv.Height > DataTransfer.ScreenBoardHeight)
            {
                if (DataTransfer.ScreenBoardHeight - pv.Height < 0)
                {
                    return false;
                }
                else
                {
                    p.Y = DataTransfer.ScreenBoardHeight - pv.Height;
                }
            }

            //if (pv.Right > DataTransfer.inchBoardWidth && pv.Left <= DataTransfer.inchBoardWidth)//判断是否压红线
            //{
            //    p.X = DataTransfer.inchBoardWidth + 10;
            //    p.Y = (p.Y < 0) || (p.Y > DataTransfer.inchBoardHeight) ? 10 : p.Y;
            //}

            return result;
        }

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        void picV_MouseDown(object sender, MouseEventArgs e)//按下左键，准备移动
        {
            if (e.Button == MouseButtons.Left)
            {
                PicView _curPicView;            //当前被选中的要进行移动的图片          
                _curPicView = (PicView)sender;

                if (_curPicView.Type == 0 && _multilSelectTPicV != null)
                {
                    CancelMutilSelect();
                }


                _curPicView.Focus();
                _curPicView.Select();

                //启动移动图片
                ReleaseCapture();
                SendMessage(_curPicView.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
                if (_PicEnablePoint.X != -1)
                {
                    _curPicView.Location = _PicEnablePoint;

                    //写入实际值2012 12 20
                   PicView pvLeft= _ListPicView.Where(p=>(p.Location.X+p.Width)==_PicEnablePoint.X).FirstOrDefault();
                   PicView pvTop = _ListPicView.Where(p => (p.Location.Y + p.Height)== _PicEnablePoint.Y).FirstOrDefault();
                   if (pvLeft != null && pvTop!=null)
                   {

                       _curPicView.PixFactX = pvLeft.PixFactX + pvLeft.PixFacWidth;
                       _curPicView.PixFactY = pvTop.PixFactY +  pvTop.PixFacHeight ;

                   }
                   else if (pvLeft != null && pvTop == null)
                   {
                       _curPicView.PixFactX = pvLeft.PixFactX +  pvLeft.PixFacWidth ;
                       _curPicView.PixFactY = Convert.ToInt32((decimal)_PicEnablePoint.Y / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                   }
                   else if (pvLeft == null && pvTop != null)
                   {
                       _curPicView.PixFactX = Convert.ToInt32((decimal)_PicEnablePoint.X / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI); ;
                       _curPicView.PixFactY = pvTop.PixFactY +pvTop.PixFacHeight;
                   }
                   else
                   {

                       _curPicView.PixFactX = Convert.ToInt32((decimal)_PicEnablePoint.X / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                       _curPicView.PixFactY = Convert.ToInt32((decimal)_PicEnablePoint.Y / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                   }

                    
                }
                _PicEnablePoint = new Point(-1, -1);
                _curPicView.LeftAnchor = false;
                _curPicView.RightAnchor = false;
                _curPicView.UpAnchor = false;
                _curPicView.DownAnchor = false;
                ShowWraste();
            }

        }

        private void ShowWraste()//显示浪费率
        {
            int effectArea, MaxX, totalArea,FactMaxX;//有效面积与最大X值、以及总面积
            float wraste;
            Color wTextColor = Color.YellowGreen;//浪费率的显示颜色

            effectArea = _ListPicView.Where(pv => pv.IsOutRedLine == false).Sum(pv => pv.Width * pv.Height);
            try
            {
                MaxX = _ListPicView.Where(pv => pv.IsOutRedLine == false).Max(pv => pv.Right);
                FactMaxX = _ListPicView.Where(pv => pv.IsOutRedLine == false).Max(pvv=>pvv.PixFactX+pvv.PixFacWidth);
            }
            catch (InvalidOperationException)//ListPicView.Where(pv => pv.IsOutRedLine == false)为空    
            {
                _view.ShowWaste(string.Format("{0:0.00}%", 0), wTextColor);
                return;
            }
            _curMaxX = MaxX;
            _FactMaxX = FactMaxX;
            totalArea = MaxX * DataTransfer.ScreenBoardHeight;
            wraste = 1 - ((float)effectArea / (float)totalArea);
            if (wraste < 0)
            {
                wraste = 0;
            }
            _curWraste = wraste;

            if (wraste > 0.1)
            {
                wTextColor = Color.Red;
            }
            _view.ShowWaste(string.Format("{0:0.00}%", wraste * 100), wTextColor);
        }
        #endregion

        /// <summary>
        /// //将拖到大板上的图片将其放到合适的位置
        /// </summary>
        /// <param name="photoList"></param>
        /// <param name="mouseFormBigBoardPoint"></param>
        internal void DrawPic(List<PhotoInfo_PBDCT> photoList, Point mouseFormBigBoardPoint)
        {
            int overPicCount = 1;//一次拖多张图片放到拼板区或时，如果出现重叠，则将图片放到红线右边上时需要有一个减
            foreach (var pinfo in photoList)
            {
                PicView picV = new PicView(pinfo, mouseFormBigBoardPoint);
                Point tempPoint = picV.Location;
                if (!GetSuitPoint(ref tempPoint, picV))
                {
                    //旋转后再试
                    int width, height;
                    width = picV.Width;
                    height = picV.Height;

                    if (DataTransfer.curTemplateInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)//条码在左右
                    {
                        width -= DataTransfer.BarCodePixWidth;
                        height += DataTransfer.BarCodePixWidth;
                    }
                    else if (DataTransfer.curTemplateInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)//条码在上下
                    {
                        width += DataTransfer.BarCodePixWidth;
                        height -= DataTransfer.BarCodePixWidth;
                    }

                    picV.Width = height;
                    picV.Height = width;

                    if (!GetSuitPoint(ref tempPoint, picV))
                    {
                        MessageBox.Show("此大板不能放下此图片,请另选一模块");
                        return;
                    }
                    else//旋转后OK
                    {
                        picV.IsWhirl = true;
                    }
                }

                picV.Location = tempPoint;
                if (!picV.IsOutRedLine)
                {
                    bool result = IsInRect(picV);
                    if (result)//如果重叠就将图片放到红线外
                    {
                        picV.Location = new Point(DataTransfer.ScreenBoardLength + (overPicCount * 10), (overPicCount - 1) * 10);
                        overPicCount++;
                    }
                }


                _ListPicView.Add(picV);

                pinfo.IsInBoard = true;

                picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
                picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

                picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
                picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);
                _view.ShowPic(picV);
                ShowWraste();

                //检果访照片所对应的产品的其它照片是否都已放到大板上
                CheckOrdersPhotoIsAllInBoard(picV.PInfo.OrderProductId);
            }

            if (overPicCount > 1)
            {
                //AutoPB_InBoard();
            }
        }

        /// <summary>
        /// 将一个图片放到大板上
        /// </summary>
        /// <param name="picV"></param>
        private void AddPicToPanel(PicView picV)
        {
            //if (!picV.IsOutRedLine)
            //{
            //    //_OveredPointList.Add(picV.Location);
            //    _OveredPointList = _OveredPointList.Distinct().ToList();
            //}

            _ListPicView.Add(picV);

            picV.PInfo.IsInBoard = true;

            picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
            picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
            picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

            picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
            picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);
            _view.ShowPic(picV);
            ShowWraste();

            //检果访照片所对应的产品的其它照片是否都已放到大板上
            CheckOrdersPhotoIsAllInBoard(picV.PInfo.OrderProductId);
        }

        /// <summary>
        /// 旋转图片
        /// </summary>
        /// <param name="oldPic"></param>
        /// <returns></returns>
        private PicView CircumrotatePic(PicView oldPic)
        {
            //旋转后再试
            int width, height, pixWidth,pixHeight;
            width = oldPic.Width;
            height = oldPic.Height;
            pixWidth = oldPic.PixFacWidth;
            pixHeight = oldPic.PixFacHeight;
            if (DataTransfer.curTemplateInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft)//条码在左右
            {
                width -= DataTransfer.BarCodePixWidth;
                height += DataTransfer.BarCodePixWidth;
                pixWidth -= DataTransfer.BarCodePixFactWidth;
                pixHeight += DataTransfer.BarCodePixFactWidth; ;
            }
            else if (DataTransfer.curTemplateInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom)//条码在上下
            {
                width += DataTransfer.BarCodePixWidth;
                height -= DataTransfer.BarCodePixWidth;
                pixWidth += DataTransfer.BarCodePixFactWidth;
                pixHeight -= DataTransfer.BarCodePixFactWidth; ;
            }


            oldPic.Width = height;
            oldPic.Height = width;
            //oldPic.PixFacWidth = pixHeight;
            //oldPic.PixFacHeight = pixWidth;
            return oldPic;
        }



        /// <summary>
        /// 已被放了图片的坐标点
        /// </summary>
        //private List<PicView> _OveredPointList = new List<PicView>();
        /// <summary>
        /// 将托动到大板上的图片放到一个最合适的位置
        /// </summary>
        /// <param name="picV"></param>
        private void SetPicAtSuitPostion(PicView picV)
        {
            bool isSuss = false;
            //所有可能的坐标
            List<Point> LocationList = new List<Point>();
            List<Point> FactLocationList = new List<Point>();
            LocationList.Add(new Point(0, 0));
            //FactLocationList.Add(new Point(0, 0));
            foreach (var pic in _ListPicView.Where(p => !p.IsOutRedLine).ToList())
            {
                LocationList.Add(pic.Point2);
                LocationList.Add(pic.Point4);
                LocationList.Add(new Point(pic.Point2.X, 0));
                LocationList.Add(new Point(0, pic.Point4.Y));
                FactLocationList.Add(pic.PixPoint2);
                FactLocationList.Add(pic.PixPoint4);
                //FactLocationList.Add(new Point(pic.Point2.X, 0));
                //FactLocationList.Add(new Point(0, pic.Point4.Y));
            }
            LocationList = LocationList.Except(_ListPicView.Where(p => !p.IsOutRedLine).Select(p => p.Location).ToList()).ToList();
            FactLocationList = FactLocationList.Except(_ListPicView.Where(p => !p.IsOutRedLine).Select(p => p.PixLocation).ToList()).ToList();
            //清除重复
            LocationList = LocationList.Distinct().ToList();
            FactLocationList = FactLocationList.Distinct().ToList();
            //排序
            LocationList = LocationList.OrderBy(p => p.X).ThenBy(p => p.Y).ToList();
            FactLocationList = FactLocationList.OrderBy(p=>p.X).ThenBy(p=>p.Y).ToList();
            foreach (var point in LocationList)
            {
                picV.Location = point;
                picV.PixFactX = Convert.ToInt32((decimal)point.X / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                picV.PixFactY = Convert.ToInt32((decimal)point.Y / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                if (IsInRect(picV))//如果重叠，就旋转一下再试
                {
                    picV = CircumrotatePic(picV);
                    if (IsInRect(picV))//如果旋转,还是重叠，则应旋转回来，再继续试下一下结点
                    {
                        picV = CircumrotatePic(picV);
                        continue;
                    }
                    else//旋转后不重叠
                    {
                        picV.IsWhirl = true;
                        isSuss = true;
                        break;
                    }
                }
                else//不重叠
                {
                    isSuss = true;
                    break;
                }
            }
            if (!isSuss)//如果全部试完都还没有成功，则将图片放到红线外
            {
                picV.Location = new Point(DataTransfer.ScreenBoardLength + 10, 5);
            }


            PicView pvLeft = _ListPicView.Where(p => (p.Location.X + p.Width == picV.Location.X)).FirstOrDefault();
            PicView pvTop = _ListPicView.Where(p => (p.Location.Y + p.Height == picV.Location.Y)).FirstOrDefault();
            if (pvLeft != null && pvTop != null)
            {

                picV.PixFactX = pvLeft.PixFactX +  pvLeft.PixFacWidth;
                picV.PixFactY = pvTop.PixFactY + pvTop.PixFacHeight;

            }
            else if (pvLeft != null && pvTop == null)
            {
                picV.PixFactX = pvLeft.PixFactX +  pvLeft.PixFacWidth;
                picV.PixFactY = Convert.ToInt32((decimal)picV.Location.Y / DataTransfer.PERPIXEL*DataTransfer.CurPrinerInfo.PDPI);
            }
            else if (pvLeft == null && pvTop != null)
            {
                picV.PixFactX = Convert.ToInt32((decimal)picV.Location.X / DataTransfer.PERPIXEL*DataTransfer.CurPrinerInfo.PDPI); ;
                picV.PixFactY = pvTop.PixFactY +  pvTop.PixFacHeight;
            }
            else
            {
                picV.PixFactX = Convert.ToInt32((decimal)picV.Location.X / DataTransfer.PERPIXEL*DataTransfer.CurPrinerInfo.PDPI);
                picV.PixFactY = Convert.ToInt32((decimal)picV.Location.Y / DataTransfer.PERPIXEL*DataTransfer.CurPrinerInfo.PDPI);
            }

            AddPicToPanel(picV);

        }


        internal void NewDrawPic(List<PhotoInfo_PBDCT> photoList, Point mouseFormBigBoardPoint)
        {
            int overPicCount = 1;//一次拖多张图片放到拼板区或时，如果出现重叠，则将图片放到红线右边上时需要有一个减
            //近照高宽大小排倒序
            photoList = photoList.OrderByDescending(p => p.Photo_Base_Info.Height).ThenByDescending(p => p.Photo_Base_Info.Width).ToList();
            foreach (var pinfo in photoList)
            {
                PicView picV = new PicView(pinfo, mouseFormBigBoardPoint);
                Point tempPoint = picV.Location;
                if (!GetSuitPoint(ref tempPoint, picV))
                {
                    //旋转后再试
                    picV = CircumrotatePic(picV);

                    if (!GetSuitPoint(ref tempPoint, picV))
                    {
                        picV.Dispose();//释放相应的资源
                        MessageBox.Show("此大板不能放下此图片,请另选一模块");
                        return;
                    }
                    else//旋转后OK
                    {
                        picV.IsWhirl = true;
                    }
                }

                picV.Location = tempPoint;

               
                if (!picV.IsOutRedLine)
                {
                    SetPicAtSuitPostion(picV);
                }
                else
                {
                    AddPicToPanel(picV);
                }
            }

            if (overPicCount > 1)
            {
                //AutoPB_InBoard();
            }
        }

        /// <summary>
        /// 将在板上的图片再用来自动拼板（排序）
        /// </summary>
        private void AutoPB_InBoard()
        {
            //List<PhotoInfo_PBDCT> listResult;
            //List<PhotoInfo_PBDCT> at = _ListPicView.Select(o => o.PInfo).ToList();
            //ClearBigBoard();
            //listResult = _bll.AutoPinS(at, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo);
            //if (listResult.Count > 0)
            //{
            //    ResolveAutoPBResult(listResult);
            //}
        }

        /// <summary>
        /// 检查产品是否全在大板上
        /// </summary>
        /// <param name="OrderProductId"></param>
        private void CheckOrdersPhotoIsAllInBoard(int OrderProductId)
        {
            OrderInfo_PBDCT oi = _curBindOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == OrderProductId);
            if (oi != null)
            {
                if (oi.PhotoList.Count(p => !p.IsInBoard) == 0)//全在大板上
                {
                    if (oi.IsAllPhotoInBoard != 2)
                    {
                        oi.IsAllPhotoInBoard = 2;
                        _view.RushOrderGrid();
                    }
                }
                else
                {
                    if (oi.PhotoList.Count(p => p.IsInBoard) == 0)//一个都没有在大板上
                    {
                        if (oi.IsAllPhotoInBoard != 0)
                        {
                            oi.IsAllPhotoInBoard = 0;
                            _view.RushOrderGrid();
                        }
                    }
                    else//一部分在大板上
                    {
                        if (oi.IsAllPhotoInBoard != 1)
                        {
                            oi.IsAllPhotoInBoard = 1;
                            _view.RushOrderGrid();
                        }
                    }

                }
            }
        }

        /// <summary>
        /// /清空大板
        /// </summary>
        internal void ClearBigBoard()
        {
            //foreach (var picv in _ListPicView)
            //{
            //    //PhotoInfo_PBDCT piTemp = _photosList.Find(delegate(PhotoInfo_PinBan pi) { if (pi.PhotoId == picv.PInfo.PhotoId)return true; else return false; });
            //    OrderInfo_PBDCT oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == picv.PInfo.Photo_Base_Info.OrderProductId);
            //    if (oi != null)
            //    {
            //        PhotoInfo_PBDCT piTemp = oi.PhotoList.FirstOrDefault(p => p.PhotoId == picv.PInfo.PhotoId);
            //        if (piTemp != null)
            //        {
            //            piTemp.IsInBoard = false;
            //            piTemp.IsWhirl = false;
            //            CheckOrdersPhotoIsAllInBoard(piTemp.OrderProductId);
            //        }
            //    }
            //}
            ////_OveredPointList.Clear();            
            //_ListPicView.Clear();
            //_view.ClearBigBoard();
            _view.ClearBigBoard2();
        }
        
        internal void ShowImgChanged()
        {
            foreach (var pv in _ListPicView)
            {
                pv.IilitialImg();
            }
        }

        /// <summary>
        /// 半自动
        /// </summary>
        internal void AutoPB()
        {
            List<OrderInfo_PBDCT> selectedOrders = _view.GetSelectedOrder;
            if (selectedOrders.Count > 0)
            {
                _selectedOrderList = selectedOrders;
            }

            if (this._selectedOrderList.Count > 0)
            {
                List<PhotoInfo_PBDCT> listResult;
                ClearBigBoard();
                listResult = _bll.AutoPinS(_selectedOrderList.Select(o => o.PhotoList).ToList(), DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, PBDataTransfer.SmallType);
                if (listResult.Count > 0)
                {
                    ResolveAutoPBResult(listResult);
                }
            }
            else
            {
                MessageBox.Show("没有需要拼板的图片");
            }
        }
        private bool CheckPhoto(List<PhotoInfo_PBDCT> inList)
        {
            int iCount = inList.Count;
            for (int i = 0; i < iCount; i++)
            {
                for (int j = i + 1; j < iCount; j++)
                {
                    //i j位置进行判断矩形是否重合
                    // return true;
                    PhotoInfo_PBDCT P1 = inList[i];
                    PhotoInfo_PBDCT P2 = inList[j];

                    //两个矩形框的边的一半
                    decimal halfP1W = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactHeigth / 2 : P1.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP2W = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactHeigth / 2 : P2.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP1H = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactWidth / 2 : P1.Photo_Base_Info.PixFactHeigth / 2;
                    decimal halfP2H = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactWidth / 2 : P2.Photo_Base_Info.PixFactHeigth / 2;

                    //两个矩形框的中心位置
                    decimal c1x = P1.Location.X + halfP1W;
                    decimal c1y = P1.Location.Y + halfP1H;
                    decimal c2x = P2.Location.X + halfP2W;
                    decimal c2y = P2.Location.Y + halfP2H;
                    //横向判断
                    if (Math.Abs(c1x - c2x) >= halfP1W + halfP2W || Math.Abs(c1y - c2y) >= halfP1H + halfP2H)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }


                }
            }
            return false;
        }
        /// <summary>
        /// 半自动
        /// </summary>
        internal void AutoNPB(double waste)
        {
            //decimal waste = 1-(decimal)0.90;
            List<OrderInfo_PBDCT> selectedOrders = _view.GetSelectedOrder;
            if (selectedOrders.Count > 0)
            {
                _selectedOrderList = selectedOrders;
            }

            if (this._selectedOrderList.Count > 0)
            {
                List<PhotoInfo_PBDCT> listResult;
                ClearBigBoard();
                decimal outWaste = 0;
                int outLength = 0;
                int inlengthPre=Convert.ToInt32(Convert.ToDecimal(SmallERP.PinBan.PBDataTransfer.MinLengthPrs));
                listResult = _bll.AutoPinSN(_selectedOrderList.Select(o => o.PhotoList).ToList(), DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (decimal)waste, out outWaste, out outLength, inlengthPre);
                if (listResult!=null&&!CheckPhoto(listResult))
                {


                    if (listResult == null || listResult.Count == 0)
                    {
                        _selectedOrderList.Select(o => o.PhotoList).ToList().ForEach(p=>p.ForEach(f=>f.IsInBoard=false));
                        //List<PhotoInfo_PBDCT> effectPi_PinBan = _selectedOrderList.Select(pv => pv.PhotoList).ToList();
                        //RushBindNew(_selectedOrderList.Select(o => o.PhotoList).ToList());
                        //effectPi_PinBan.Clear();//清出LJ
                        MessageBox.Show("不能找到浪费率为" + waste  + "%以下的版");
                        
                    }
                    else
                    {
                        if (listResult.Count > 0)
                        {
                            ResolveAutoPBResult2(listResult);
                        }
                    }
                }
                else
                {
                    if (listResult == null ||listResult.Count == 0)
                    {
                        MessageBox.Show("不能找到浪费率为" + waste * 100 + "%以下的版");
                    }
                    else
                    {
                        listResult.ForEach(p => p.IsInBoard = false);
                    }
                    //MessageBox.Show("不能找到浪费率为" + waste * 100 + "%以下的版");
                }
            }
            else
            {
                MessageBox.Show("没有需要拼板的图片");
            }

        }

        private void ResolveAutoPBResultForAutoPinban(List<PhotoInfo_PBDCT> listResult)
        {



            //_presenter.NewDrawPic(templist, new Point(0, 0));
            RealLayoutPanel.RectangeView[] arrayRect = new RealLayoutPanel.RectangeView[listResult.Count];
            for (int i = 0; i < listResult.Count; i++)
            {
                arrayRect[i].BarcodePixelWidth = DataTransfer.BarCodePixFactWidth;
                arrayRect[i].BarcodePlace = (int)listResult[i].BarCodeStatus;
                arrayRect[i].DPI = DataTransfer.CurPrinerInfo.PDPI;
                arrayRect[i].filename = listResult[i].Photo_Base_Info.PicPath;
                arrayRect[i].isRotate = Convert.ToInt32(listResult[i].IsWhirl);
                arrayRect[i].PictureHeight = Convert.ToInt32((decimal)listResult[i].Photo_Base_Info.PixHeight / listResult[i].Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI);
                arrayRect[i].PictureID = listResult[i].PhotoId;
                arrayRect[i].PictureWidth = Convert.ToInt32((decimal)listResult[i].Photo_Base_Info.PixWidth / listResult[i].Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI);
                arrayRect[i].PixelX = listResult[i].Location.X;
                arrayRect[i].PixelY = listResult[i].Location.Y;
                //arrayRect[i].
                //arrayRect[i].Unit = toolStripComboBoxUnit.SelectedIndex;
            }
            Array array = (Array)arrayRect;
            _view.ShowPicForAuto(array);
        }
        private void ResolveAutoPBResult2(List<PhotoInfo_PBDCT> listResult)
        {
            
            

            //_presenter.NewDrawPic(templist, new Point(0, 0));
            RealLayoutPanel.RectangeView[] arrayRect = new RealLayoutPanel.RectangeView[listResult.Count];
            for (int i = 0; i < listResult.Count; i++)
            {
                arrayRect[i].BarcodePixelWidth = DataTransfer.BarCodePixFactWidth;
                arrayRect[i].BarcodePlace = (int)listResult[i].BarCodeStatus;
                arrayRect[i].DPI = DataTransfer.CurPrinerInfo.PDPI;
                arrayRect[i].filename = listResult[i].Photo_Base_Info.PicPath;
                arrayRect[i].isRotate = Convert.ToInt32(listResult[i].IsWhirl);
                arrayRect[i].PictureHeight = Convert.ToInt32((decimal)listResult[i].Photo_Base_Info.PixHeight / listResult[i].Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI);
                arrayRect[i].PictureID = listResult[i].PhotoId;
                arrayRect[i].PictureWidth = Convert.ToInt32((decimal)listResult[i].Photo_Base_Info.PixWidth / listResult[i].Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI);
                arrayRect[i].PixelX = listResult[i].Location.X;
                arrayRect[i].PixelY = listResult[i].Location.Y;
               //arrayRect[i].
                //arrayRect[i].Unit = toolStripComboBoxUnit.SelectedIndex;
            }
            Array array = (Array)arrayRect;
            _view.ShowPic2(array);
        }
        /// <summary>
        /// 根据拼板结果显示图像信息
        /// </summary>
        /// <param name="listResult"></param>
        private void ResolveAutoPBResult(List<PhotoInfo_PBDCT> listResult)//解析自动拼板的结果（主要是用来显示在大纸上）
        {
            if (listResult == null || listResult.Count() == 0)
            { }
            else
            {
                foreach (PhotoInfo_PBDCT pInfo in listResult)
                {
                    int x = pInfo.Location.X;
                    int y = pInfo.Location.Y;
                    //bool iswhirl = pInfo.IsWhirl;
                    //int factW = pInfo.Photo_Base_Info.PixFactWidth;
                    //int factH = pInfo.Photo_Base_Info.PixFactHeigth;
                    //int pX=pInfo.
                    //if (iswhirl)
                    //{
                    //    pInfo.IsWhirl = false;
                    //}
                    Point screenLoaction = new Point(Convert.ToInt32(((float)pInfo.Location.X / (float)DataTransfer.CurPrinerInfo.PDPI) * DataTransfer.PERPIXEL), Convert.ToInt32(((float)pInfo.Location.Y / (float)DataTransfer.CurPrinerInfo.PDPI) * DataTransfer.PERPIXEL));
                    PicView picV = new PicView(pInfo, screenLoaction, true);
                    picV.PixFactX = x;
                    picV.PixFactY = y;
                    //pInfo.IsWhirl = iswhirl;
                   
                    
                    CheckOrdersPhotoIsAllInBoard(pInfo.OrderProductId);


                    _ListPicView.Add(picV);
                    picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
                    picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                    picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

                    picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);

                    picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);


                    _view.ShowPic(picV);
                   
                    //pInfo.Photo_Base_Info.PixFactHeigth = factH;
                    //pInfo.Photo_Base_Info.PixFactWidth = factW;
                    //pInfo.Location = new Point(x, y); ;
                    //pInfo.IsWhirl = iswhirl;
                }
            }
            ShowWraste();
        }

        /// <summary>
        /// 打印当前大板
        /// </summary>
        internal void PintCurBoard()
        {
            if (_ListPicView.Count == 0)
            {
                return;
            }
            int result = 0;
            float RealBoardLength = 0;//板的真实长度（对应高度（或宽度））
            if (_curMaxX < 1)
            {
                return;
            }
            _FactMaxX = _ListPicView.Where(p=>!p.IsOutRedLine).Max(m => m.PixFactX + m.PixFacWidth);
            RealBoardLength = (float)_curMaxX / DataTransfer.PERPIXEL;
            RealBoardLength = (float)_FactMaxX / DataTransfer.CurPrinerInfo.PDPI;
            
            PicView tP = _ListPicView.FirstOrDefault(pv => pv.Type == 1);
            if (tP != null)
            {
                MessageBox.Show("有框选图片，请单击空白处，再打印！");
                return;
            }

            //List<PhotoInfo_PBDCT> effectPi_PinBan = _ListPicView.Where(pv => pv.IsOutRedLine == false && pv.Type != 1).Select(pv => pv.PInfo).ToList();
            List<PhotoInfo_PBDCT> effectPi_PinBan = new List<PhotoInfo_PBDCT>();
            foreach (PicView pic in _ListPicView.Where(pv => pv.IsOutRedLine == false && pv.Type != 1))
            {
                PhotoInfo_PBDCT p = pic.PInfo;
                int x, y;
                x = Convert.ToInt32((float)p.Location.X / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                y = (int)((float)p.Location.Y / DataTransfer.PERPIXEL * DataTransfer.CurPrinerInfo.PDPI);
                pic.PInfo.Location = new Point(pic.PixFactX, pic.PixFactY);
                effectPi_PinBan.Add(pic.PInfo);
            } 

            if (effectPi_PinBan.Count > 0)
            {
                result = _bll.CreateBoardHand(effectPi_PinBan, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, _curWraste, RealBoardLength);
                if (result == 1)
                {
                    MessageBox.Show("添加大板信息时出错，请清空版面重新拼版");
                }
                else if (result == -1)//拼板超出了范围
                {
                    effectPi_PinBan.Clear();//清出LJ
                    RushBind(false);
                    //ClearBigBoard();
                }
                else if (result == -2)//加密失败
                {
                    //MessageBox.Show("服务器加密狗信息出错！");
                }
                else//result=0
                {
                    //1.清除大板上所有的图片，2清空ListPicView,3重新取得_photosList,
                    //_photosList = _photosList.Except(effectPi_PinBan).ToList();
                    RushBindNew(effectPi_PinBan);
                    //effectPi_PinBan.Clear();//清出LJ

                    //_curShowPhotoList = _photosList;
                    //RushBind(true);
                    ClearBigBoard();

                }
            }
        }
        internal void PintCurBoard(List<PhotoInfo_PBDCT> effectPi_PinBan, int BoardFactLength)
        {
          
            int result = 0;
            
          
            int RealBoardLength = BoardFactLength;
           


            if (effectPi_PinBan.Count > 0)
            {
                result = _bll.CreateBoardHand(effectPi_PinBan, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, _curWraste, RealBoardLength);
                if (result == 1)
                {
                    MessageBox.Show("添加大板信息时出错，请清空版面重新拼版");
                }
                else if (result == -1)//拼板超出了范围
                {
                   // effectPi_PinBan.Clear();//清出LJ
                    RushBind(false);
                    //ClearBigBoard();
                }
                else if (result == -2)//加密失败
                {
                    //MessageBox.Show("服务器加密狗信息出错！");
                }
                else//result=0
                {
                    //1.清除大板上所有的图片，2清空ListPicView,3重新取得_photosList,
                    //_photosList = _photosList.Except(effectPi_PinBan).ToList();
                    RushBindNew2(effectPi_PinBan);
                    //effectPi_PinBan.Clear();//清出LJ

                    //_curShowPhotoList = _photosList;
                    //RushBind(true);
                    //ClearBigBoard();

                }
            }
        }
        internal void PintCurBoard(RealLayoutPanel.RectangeView[] arrRV, decimal waste,int BoardType=0)
        {
            List<PhotoInfo_PBDCT> InBoardlistPhoto = new List<PhotoInfo_PBDCT>();
            List<PhotoInfo_PBDCT> listPhoto = new List<PhotoInfo_PBDCT>();
            _allOrderList.ForEach(p => listPhoto.AddRange(p.PhotoList));
            int maxL = 0;
            foreach (var rv in arrRV)
            {
                PhotoInfo_PBDCT pInBoard = listPhoto.FirstOrDefault(p => p.PhotoId == rv.PictureID);
                pInBoard.IsInBoard = true;
                pInBoard.IsWhirl = Convert.ToBoolean(rv.isRotate);
                pInBoard.Location = new Point(rv.PixelX, rv.PixelY);
                if (rv.BarcodePlace == 0)
                {
                    pInBoard.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.RightOrLeft;
                }
                else if (rv.BarcodePlace == 1)
                {
                    pInBoard.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom;

                }
                else
                {
                    pInBoard.BarCodeStatus = SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode;

                }
                if (rv.PixelX + rv.PixelWidth > maxL)
                {
                    maxL = rv.PixelX + rv.PixelWidth;
                }
                InBoardlistPhoto.Add(pInBoard);

            }
            int result = 0;


            int RealBoardLength = maxL;



            if (InBoardlistPhoto.Count > 0)
            {
                result = _bll.CreateBoardHand(InBoardlistPhoto, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (float)waste, RealBoardLength,BoardType);
                if (result == 1)
                {
                    MessageBox.Show("添加大板信息时出错，请清空版面重新拼版");
                }
                else if (result == -1)//拼板超出了范围
                {
                    // effectPi_PinBan.Clear();//清出LJ
                    RushBind(false);
                    //ClearBigBoard();
                }
                else if (result == -2)//加密失败
                {
                    //MessageBox.Show("服务器加密狗信息出错！");
                }
                else//result=0
                {
                    //1.清除大板上所有的图片，2清空ListPicView,3重新取得_photosList,
                    //_photosList = _photosList.Except(effectPi_PinBan).ToList();
                    RushBindNew2(InBoardlistPhoto);
                    //effectPi_PinBan.Clear();//清出LJ

                    //_curShowPhotoList = _photosList;
                    //RushBind(true);
                    //ClearBigBoard();

                }
            }
        }
        internal void RushBindNew2(List<PhotoInfo_PBDCT> inList)
        {
            _view.ClearBigBoard2();
            _isNewPhotoList = true;

            List<OrderInfo_PBDCT> tempList = new List<OrderInfo_PBDCT>();
            foreach (OrderInfo_PBDCT or in _allOrderList)
            {
                OrderInfo_PBDCT tempOrder = or;
                List<PhotoInfo_PBDCT> tempPhotoList = new List<PhotoInfo_PBDCT>();
                foreach (PhotoInfo_PBDCT ph in or.PhotoList)
                {
                    if (inList.FirstOrDefault(p => p.PhotoId == ph.PhotoId) != null)
                    {
                        //or.PhotoList.Remove(ph);
                    }
                    else
                    {
                        tempPhotoList.Add(ph);
                    }

                }
                if (tempPhotoList.Count > 0)
                {
                    tempOrder.PhotoList = tempPhotoList;
                    tempList.Add(tempOrder);
                }
               
               

            }
            
            //foreach (OrderInfo_PBDCT or in _allOrderList)
            //{
            //    if (or.PhotoList.Count > 0)
            //    {
            //        tempList.Add(or);
            //    }

            //}
            _allOrderList = tempList;
            BindSuitOrder(_allOrderList);
            BindPhotoSizeList();
            _view.SetSelected();
        }
        /// <summary>
        /// //根据当前的模板得到合适的照片列表
        /// </summary>
        public void GetSuitPhotosByTemplate(string BoardRemark)
        {
            string templateName = _view.SelectTemplateName;
            DataTransfer.curTemplateInfo = DataTransfer.BoardTempalteList.FirstOrDefault(t => t.TemplateName == templateName);
            DataTransfer.curTemplateInfo.BoardNameRemark = BoardRemark;

            _view.InitCtlsLoaction();
            RushBind();
        }

        /// <summary>
        /// 复制产品
        /// </summary>
        /// <param name="SelectOrderList"></param>
        /// <param name="AddNum"></param>
        internal void CopyOrder(List<OrderInfo_PBDCT> SelectOrderList, int AddNum)
        {
            int result = _bll.CopyOrder(SelectOrderList, AddNum);
            if (result == 1)//成功，就刷新界面
            {
                RushBind();
            }
            else
            {
                //报相应的错误信息
                MessageBox.Show("复制出错");
            }
        }

        /// <summary>
        /// 复制照片
        /// </summary>
        /// <param name="SelectOrderList"></param>
        /// <param name="AddNum"></param>
        internal void CopyPhoto(List<PhotoInfo_PBDCT> SelectPhotoList, int AddNum)
        {
            int result = _bll.CopyPhoto(SelectPhotoList, AddNum);
            if (result == 1)//成功，就刷新界面
            {
                RushBind();
            }
            else
            {
                //报相应的错误信息
                MessageBox.Show("复制出错");
            }
        }

        /// <summary>
        /// 删除选中的照片
        /// </summary>
        /// <param name="SelectOrderList"></param>
        internal void DeletePhoto(List<PhotoInfo_PBDCT> SelectPhotoList)
        {
            int result = _bll.DeletePhoto(SelectPhotoList);
            if (result == 1)//成功，就刷新界面
            {
                RushBind();
            }
            else if (result == -1)
            {
                //报相应的错误信息
                MessageBox.Show("没有需要删除的照片");
            }
            else if (result == -2)
            {
                MessageBox.Show("提交数据时出错");
            }
        }

        /// <summary>
        /// 删除选中的定单
        /// </summary>
        /// <param name="SelectOrderList"></param>
        internal void DeleteOrder(List<OrderInfo_PBDCT> SelectOrderList)
        {
            int result = _bll.DeleteOrder(SelectOrderList);
            if (result == 1)//成功，就刷新界面
            {
                RushBind();
            }
            else
            {
                //报相应的错误信息
                MessageBox.Show("提交数据时出错");
            }
        }


        /// <summary>
        /// 根据选择的产品列表然后绑定相应的照片
        /// </summary>
        /// <param name="selectedOrders"></param>
        internal void SelectOrder()
        {
            List<OrderInfo_PBDCT> selectedOrders = _view.GetSelectedOrder;
            if (selectedOrders.Count > 0)
            {
                _selectedOrderList = selectedOrders;
            }
            else
            {
                _selectedOrderList = new List<OrderInfo_PBDCT>();
            }

            BindPhotoGV();

        }

        /// <summary>
        /// 绑定照片列表
        /// </summary>
        private void BindPhotoGV()
        {
            if (_selectedOrderList.Count > 0)
            {
                List<PhotoInfo_PBDCT> BindPhotoList = new List<PhotoInfo_PBDCT>();
                foreach (var oi in _selectedOrderList)
                {
                    BindPhotoList.AddRange(oi.PhotoList);
                }
                if (BindPhotoList.Count > 0)
                {
                    _view.BindPhotoList(BindPhotoList);
                }
            }
        }

        /// <summary>
        /// 根据输入的关键字快迅过滤产品
        /// </summary>
        internal void filtrateOrderName()
        {
            string filtrateString = _view.GetFiltrateString;
            if (string.IsNullOrEmpty(filtrateString))
            {
                //就绑定所有的
                BindSuitOrder(_allOrderList);
            }
            else
            {
                //从所有的产品列表中过滤
                if (_curBindOrderList.Count < 1)//当前的显示列表为空时就从所有产品列表中去
                {
                    BindSuitOrder(_allOrderList.Where(o => o.order_Base_Info.OrderName.Contains(filtrateString)).ToList());
                }
                else
                {
                    BindSuitOrder(_curBindOrderList.Where(o => o.order_Base_Info.OrderName.Contains(filtrateString)).ToList());
                }

            }
        }

        internal int GetTotalPhotoCount()
        {
            return _allOrderList.Select(o => o.PhotoList.Count()).Sum(o => o);
        }

        /// <summary>
        /// 绑定各种选择、筛选或是操作的产品列表
        /// </summary>
        /// <param name="soruceList"></param>
        private void BindSuitOrder(List<OrderInfo_PBDCT> soruceList)
        {
          
            _curBindOrderList = soruceList;

            _view.BindPhotoSizeList(_photoSizeList);
            _view.BindOrderList(_curBindOrderList);
            _view.SetSelected();
           
        }
        /// <summary>
        /// 绑定各种选择、筛选或是操作的产品列表
        /// </summary>
        /// <param name="soruceList"></param>
        private void BindSuitOrder2(List<OrderInfo_PBDCT> soruceList)
        {
            //_view.SetSelected();
            _curBindOrderList = soruceList;

            _view.BindPhotoSizeList(_photoSizeList);
            _view.BindOrderList(_curBindOrderList);

        }
        /// <summary>
        /// 绑定所有照片的尺寸列表
        /// </summary>
        private void BindPhotoSizeList()
        {
          
            List<PhotoInfo_PBDCT> AllPhotoList = new List<PhotoInfo_PBDCT>();
            _allOrderList.ForEach(o => AllPhotoList.AddRange(o.PhotoList));
            //_photoSizeList = AllPhotoList.Where(p=>p.IsInBoard!=true).Select(p => p.PhotoSize).Distinct(new MyPhotoSizeComparer()).OrderBy(s => Convert.ToSingle(s.Substring(0, s.IndexOf("X")))).ThenBy(s => Convert.ToSingle(s.Substring(s.IndexOf("X") + 1))).ToList();
            _photoSizeList = AllPhotoList.Where(p=>p.IsInBoard!=true).Select(p => p.PhotoSizeAll).Distinct(new MyPhotoSizeComparer()).OrderBy(s => Convert.ToSingle(s.Substring(0,s.IndexOf("(")).Substring(0, s.IndexOf("X")))).ThenBy(s => Convert.ToSingle(s.Substring(0,s.IndexOf("(")).Substring(s.IndexOf("X") + 1))).ToList();

            _view.BindPhotoSizeList(_photoSizeList);
        }

        class MyPhotoSizeComparer : IEqualityComparer<string>
        {
            #region IEqualityComparer<string> 成员

            public bool Equals(string x, string y)
            {
                string[] xWH = x.Split(new char[] { 'X' });
                string[] yWH = y.Split(new char[] { 'X' });
                if (xWH.Length <= 1 || yWH.Length <= 1)
                {
                    return true;
                }

                if ((xWH[0] == yWH[0] && xWH[1] == yWH[1]) || (xWH[0] == yWH[1] && xWH[1] == yWH[0]))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            public int GetHashCode(string obj)
            {
                //return obj.GetHashCode();
                return -1;
            }

            #endregion
        }

        internal void FilterPhotoSize()
        {
            string strSelectPhotoSize = _view.SelectPhotoSize.Substring(0, _view.SelectPhotoSize.IndexOf("("));
            if (!string.IsNullOrEmpty(strSelectPhotoSize))
            {
                int inx = strSelectPhotoSize.IndexOf("X");
                string strPSTemp = strSelectPhotoSize.Substring(inx + 1) + "X" + strSelectPhotoSize.Substring(0, inx);
                List<PhotoInfo_PBDCT> AllPhotoList = new List<PhotoInfo_PBDCT>();
                _allOrderList.ForEach(o => AllPhotoList.AddRange(o.PhotoList));
                List<PhotoInfo_PBDCT> _curShowPhotoList = AllPhotoList.Where(p => p.PhotoSize == strSelectPhotoSize || p.PhotoSize == strPSTemp).ToList();
                _view.BindPhotoList(_curShowPhotoList);
            }
        }

        /// <summary>
        /// 查看返工列表
        /// </summary>
        internal void BindRebackOrderList()
        {
            //RushBind();
            BindSuitOrder(_allOrderList.Where(o => o.HasRebackOrder).ToList());
        }

        /// <summary>
        /// 查看清柜列表
        /// </summary>
        internal void BindClearBoxOrderList()
        {
            //RushBind();
            BindSuitOrder(_allOrderList.Where(o => o.IsClearBox).ToList());
        }

        internal void SwitchPrinter()
        {
            IniliData();
        }

        internal void TemplateManage()
        {
            //跳出建模板的界面
            FrmTemplateManager frmTempalteManger = new FrmTemplateManager(_view._OperateDb);
            frmTempalteManger.ShowDialog();
            BindBoardTemplate();
        }
        BackgroundWorker bgwFullPB = new BackgroundWorker();
        Timer timeFullPB = new Timer();
        double CurrWaste = 0;
        /// <summary>
        /// 全自动拼板
        /// </summary>
        internal void FullAutoPB(double waste)
        {
            currPhotoList = _allOrderList.Select(o => o.PhotoList).ToList();
            CurrWaste = waste;
            timeFullPB.Enabled = true;

            //FrmFullAutoPB frmFPB = new FrmFullAutoPB();
            //frmFPB.ShowDialog();

            ////全自动完成后需要刷新列表
            //RushBind();
        }
        internal void FullAutoPB()
        {
            FrmAutoPinBanSetting frm = new FrmAutoPinBanSetting();
            frm.CurrOrderList = _allOrderList;
            frm._OperateDb = _view._OperateDb;
            frm.Print += new FrmAutoPinBanSetting.PrintPhotosListToSc(frm_Print);
            frm.ShowDialog();
            RushBind();
            

        }

        void frm_Print(List<PhotoInfo_PBDCT> list)
        {
            //ClearBigBoard();
            List<PhotoInfo_PBDCT> copyList = new List<PhotoInfo_PBDCT>();
            foreach (PhotoInfo_PBDCT photo in list)
            {
                PhotoInfo_PBDCT copyPhoto = new PhotoInfo_PBDCT();
                copyPhoto.PhotoId = photo.PhotoId;
                copyPhoto.PhotoName = photo.PhotoName;
                copyPhoto.IsWhirl = photo.IsWhirl;
                copyPhoto.Location = photo.Location;
                copyPhoto.BarCodeStatus = photo.BarCodeStatus;
                copyPhoto.Photo_Base_Info = new PhotoDCT();
                copyPhoto.Photo_Base_Info.PhotoId = photo.Photo_Base_Info.PhotoId;
                copyPhoto.Photo_Base_Info.PixFactHeigth = photo.Photo_Base_Info.PixFactHeigth;
                copyPhoto.Photo_Base_Info.PixFactWidth = photo.Photo_Base_Info.PixFactWidth;
                copyPhoto.Photo_Base_Info.PixHeight = photo.Photo_Base_Info.PixHeight;
                copyPhoto.Photo_Base_Info.PixWidth = photo.Photo_Base_Info.PixWidth;
                copyPhoto.Photo_Base_Info.Width = photo.Photo_Base_Info.Width;
                copyPhoto.Photo_Base_Info.Height = photo.Photo_Base_Info.Height;
                copyPhoto.Photo_Base_Info.DPI = photo.Photo_Base_Info.DPI;
                copyPhoto.Photo_Base_Info.OrderProductId = photo.Photo_Base_Info.OrderProductId;
                copyPhoto.Photo_Base_Info.PicPath = photo.Photo_Base_Info.PicPath;
                copyList.Add(copyPhoto);
            }
            //ResolveAutoPBResult2(copyList);
            ResolveAutoPBResultForAutoPinban(copyList);
        }
        internal int UpdatePhoto(List<PhotoInfo_PBDCT> SelectPhotoList)
        {
            RasterCodecs.Startup();
            RasterCodecs codes = new RasterCodecs();
            foreach (PhotoInfo_PBDCT photo in SelectPhotoList)
            {
                CodecsImageInfo img = null;
                img = codes.GetInformation(photo.Photo_Base_Info.PicPath, true);
                int photoXDPI = img.XResolution;
                int photoYDPI = img.YResolution;
                photo.Photo_Base_Info.Height = (float)img.Height / photoYDPI;
                photo.Photo_Base_Info.Width = (float)img.Width / photoXDPI;
                photo.Photo_Base_Info.Height = Math.Round(photo.Photo_Base_Info.Height + PlusValues, 1);
                photo.Photo_Base_Info.Width = Math.Round(photo.Photo_Base_Info.Width + PlusValues, 1);
                photo.Photo_Base_Info.PixHeight = img.Height;
                photo.Photo_Base_Info.PixWidth = img.Width;
                photo.Photo_Base_Info.DPI = photoXDPI;
                _view._OperateDb.ExecuteNonQuery("update photoinfo set  Height=" + photo.Photo_Base_Info.Height + ", Width=" + photo.Photo_Base_Info.Width + ", PixWidth=" + img.Width + ", PixHeight=" + img.Height + ", DPI=" + photoXDPI + " where photoid=" + photo.Photo_Base_Info.PhotoId);
            }
            return 0;
        }
        internal List<int> UpdatePhotoSize(List<PhotoInfo_PBDCT> SelectPhotoList)
        {
            List<int> successPhotoid = new List<int>();
            RasterCodecs.Startup();
            RasterCodecs codes = new RasterCodecs();
            foreach (PhotoInfo_PBDCT photo in SelectPhotoList)
            {
                ////CodecsImageInfo img = null;
                ////img = codes.GetInformation(photo.Photo_Base_Info.PicPath, true);
                ////int photoXDPI = img.XResolution;
                ////int photoYDPI = img.YResolution;
                //photo.Photo_Base_Info.Height = (float)img.Height / photoYDPI;
                //photo.Photo_Base_Info.Width = (float)img.Width / photoXDPI;
                //photo.Photo_Base_Info.Height = Math.Round(photo.Photo_Base_Info.Height + PlusValues, 1);
                //photo.Photo_Base_Info.Width = Math.Round(photo.Photo_Base_Info.Width + PlusValues, 1);
                //photo.Photo_Base_Info.PixHeight = img.Height;
                //photo.Photo_Base_Info.PixWidth = img.Width;
                //photo.Photo_Base_Info.DPI = photoXDPI;
                int rtnVal = _view._OperateDb.ExecuteNonQuery("update photoinfo set  Height=" + photo.Photo_Base_Info.Height + ", Width=" + photo.Photo_Base_Info.Width + ", PixWidth=" + photo.Photo_Base_Info.PixWidth + ", PixHeight=" + photo.Photo_Base_Info.PixHeight + ", DPI=" + photo.Photo_Base_Info.DPI + ",PicPath='" + photo.Photo_Base_Info.PicPath.Replace("'", "''") + "' where photoid=" + photo.Photo_Base_Info.PhotoId);
               if (rtnVal > 0)
               {
                   successPhotoid.Add(photo.Photo_Base_Info.PhotoId);
               }
            }
            return successPhotoid;
        }
        internal void ShutFullAutoPB()
        {
            timeFullPB.Enabled = false;

            bgwFullPB.CancelAsync();
        }

        public void ShowImport()
        {
            FrmImportPhoto frmImportPhoto = FrmImportPhoto.GetInstance;
            frmImportPhoto.Rush += new FrmImportPhoto.RushControl(frmImportPhoto_Rush);
            frmImportPhoto.ShowDialog();
        }
        void frmImportPhoto_Rush()
        {
            RushBind();
        }
        public void ChangePhotoStatus(int[] photoIDArray, bool isInboard)
        {
            List<PhotoInfo_PBDCT> listPhoto = new List<PhotoInfo_PBDCT>();
            _allOrderList.ForEach(p => listPhoto.AddRange(p.PhotoList));
            foreach (int photoid in photoIDArray)
            {
                if (listPhoto.Count() > 0)
                {
                    PhotoInfo_PBDCT pl = listPhoto.FirstOrDefault(p => p.PhotoId == photoid);
                    if (pl != null)
                    {
                        pl.IsInBoard = isInboard;
                    }
                }
            }
           
            BindSuitOrder(_allOrderList);
        }

        //public int SaveSelctDxfFile()
        //{

        //}

        internal bool  UpdateOrderDex(OrderInfo_PBDCT oiInfo)
        {
          return   _bll.UpdateOrderDex(oiInfo);
        }

        internal bool UpdatePhotoDxf(PhotoInfo_PBDCT photoInfoPbdct)
        {
            return _bll.UpdatePhotoDxf(photoInfoPbdct);
        }


        internal PhotoInfo_PBDCT GetPhotoInfo(int photoId)
        {
            return _bll.GetPhotoInfo(photoId);
        }
    }
}
